'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';
import { XMarkIcon, ChevronLeftIcon, ChevronRightIcon } from '@heroicons/react/24/outline';

interface ImageModalProps {
  isOpen: boolean;
  onClose: () => void;
  images: string[];
  currentIndex: number;
  onIndexChange: (index: number) => void;
  title?: string;
}

export default function ImageModal({ 
  isOpen, 
  onClose, 
  images, 
  currentIndex, 
  onIndexChange,
  title = "查看图片"
}: ImageModalProps) {
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (isOpen) {
      setLoading(true);
      // 预加载当前图片
      const img = new window.Image();
      img.onload = () => setLoading(false);
      img.onerror = () => setLoading(false);
      img.src = images[currentIndex];
      
      // 禁止页面滚动
      document.body.style.overflow = 'hidden';
      
      // 监听键盘事件
      const handleKeyDown = (e: KeyboardEvent) => {
        if (e.key === 'Escape') {
          onClose();
        } else if (e.key === 'ArrowLeft' && currentIndex > 0) {
          handlePrevious();
        } else if (e.key === 'ArrowRight' && currentIndex < images.length - 1) {
          handleNext();
        }
      };
      
      window.addEventListener('keydown', handleKeyDown);
      
      return () => {
        document.body.style.overflow = 'auto';
        window.removeEventListener('keydown', handleKeyDown);
      };
    } else {
      document.body.style.overflow = 'auto';
    }
  }, [isOpen, currentIndex, images]);

  const handlePrevious = () => {
    if (currentIndex > 0) {
      onIndexChange(currentIndex - 1);
    }
  };

  const handleNext = () => {
    if (currentIndex < images.length - 1) {
      onIndexChange(currentIndex + 1);
    }
  };

  const handleBackdropClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  if (!isOpen) return null;

  return (
    <div 
      className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center"
      onClick={handleBackdropClick}
    >
      {/* 关闭按钮 */}
      <button
        onClick={onClose}
        className="absolute top-4 right-4 z-10 bg-black/50 text-white p-2 rounded-full hover:bg-black/70 transition-colors"
        title="关闭 (Esc)"
      >
        <XMarkIcon className="w-6 h-6" />
      </button>

      {/* 图片信息 */}
      <div className="absolute top-4 left-4 z-10 bg-black/50 text-white px-4 py-2 rounded-lg">
        <p className="text-sm">{title}</p>
        {images.length > 1 && (
          <p className="text-xs text-gray-300">
            {currentIndex + 1} / {images.length}
          </p>
        )}
      </div>

      {/* 上一张按钮 */}
      {images.length > 1 && currentIndex > 0 && (
        <button
          onClick={handlePrevious}
          className="absolute left-4 top-1/2 -translate-y-1/2 z-10 bg-black/50 text-white p-3 rounded-full hover:bg-black/70 transition-colors"
          title="上一张 (←)"
        >
          <ChevronLeftIcon className="w-6 h-6" />
        </button>
      )}

      {/* 下一张按钮 */}
      {images.length > 1 && currentIndex < images.length - 1 && (
        <button
          onClick={handleNext}
          className="absolute right-4 top-1/2 -translate-y-1/2 z-10 bg-black/50 text-white p-3 rounded-full hover:bg-black/70 transition-colors"
          title="下一张 (→)"
        >
          <ChevronRightIcon className="w-6 h-6" />
        </button>
      )}

      {/* 图片容器 */}
      <div className="relative max-w-[90vw] max-h-[90vh] flex items-center justify-center">
        {loading && (
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-white"></div>
          </div>
        )}
        
        <div className="relative">
          <Image
            src={images[currentIndex]}
            alt={`图片 ${currentIndex + 1}`}
            width={1200}
            height={800}
            className="max-w-full max-h-[90vh] object-contain rounded-lg shadow-2xl"
            onLoad={() => setLoading(false)}
            onError={() => setLoading(false)}
            priority
          />
        </div>
      </div>

      {/* 缩略图导航 */}
      {images.length > 1 && (
        <div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-10">
          <div className="flex space-x-2 bg-black/50 p-2 rounded-lg max-w-[80vw] overflow-x-auto">
            {images.map((image, index) => (
              <button
                key={index}
                onClick={() => onIndexChange(index)}
                className={`relative w-12 h-12 rounded overflow-hidden border-2 transition-all ${
                  index === currentIndex 
                    ? 'border-blue-400 opacity-100' 
                    : 'border-transparent opacity-70 hover:opacity-90'
                }`}
              >
                <Image
                  src={image}
                  alt={`缩略图 ${index + 1}`}
                  fill
                  className="object-cover"
                  sizes="48px"
                />
              </button>
            ))}
          </div>
        </div>
      )}

      {/* 操作提示 */}
      <div className="absolute bottom-4 right-4 z-10 bg-black/50 text-white px-3 py-1 rounded text-xs">
        <p>ESC 关闭 • ← → 切换</p>
      </div>
    </div>
  );
}